package com.opensms.eventLogFacade.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.opensms.eventLogFacade.vo.EventLogVO;
import com.util.exceptions.InstanceNotFoundException;
import com.util.exceptions.InternalErrorException;
import com.util.sql.EntityIdentifierGenerator;
import com.util.sql.GeneralOperations;

public class StandardSQLEventLogDAO implements SQLEventLogDAO{
	private static Log log = LogFactory.getLog(StandardSQLEventLogDAO.class);
	
	public EventLogVO create(Connection connection, EventLogVO vo)
		throws InternalErrorException {
		
		PreparedStatement preparedStatement = null;
	    
        try {
           
            /* Get account identifier. */
        	log.debug("Buscar nueva clave para evento");
            EntityIdentifierGenerator entityIdentifierGenerator =
                new EntityIdentifierGenerator();
            int idLogEventos =
                entityIdentifierGenerator.nextIdentifier(connection, "logeventos");
            log.debug("Insertar evento "+ idLogEventos);
    
            /* Create "preparedStatement". */
            String queryString = "INSERT INTO logeventos " +
                " (id, fch, tipo, origen, destino, texto, observaciones) " +
                " VALUES (?, ?, ?, ?, ?, ?, ?)";
            preparedStatement = connection.prepareStatement(queryString);
            /* Fill "preparedStatement". */
            int i = 1;
            preparedStatement.setLong(i++, idLogEventos);
            preparedStatement.setTimestamp(i++, vo.getFecha());
            preparedStatement.setString(i++,""+vo.getTipo());
            preparedStatement.setString(i++,vo.getOrigen());
            preparedStatement.setString(i++, vo.getDestino());
            preparedStatement.setString(i++, vo.getTexto());
            preparedStatement.setString(i++, vo.getObservaciones());
    
            /* Execute query. */
            int insertedRows = preparedStatement.executeUpdate();
            log.debug(queryString);
    
            if (insertedRows == 0) {
                throw new SQLException("Can not add row to table 'logeventos'");
            }
    
            vo.setId(idLogEventos);
            return vo;
    
        } catch (SQLException e) {
            throw new InternalErrorException(e);
        } finally {
            GeneralOperations.closeStatement(preparedStatement);
        } 
		
	}
	
	public EventLogVO findById(Connection connection, long id)
		throws InternalErrorException, InstanceNotFoundException{
		
		PreparedStatement preparedStatement = null;
	    
        try {
           
            String queryString = "SELECT * FROM logeventos WHERE id= ?";           
            preparedStatement = connection.prepareStatement(queryString);
            /* Fill "preparedStatement". */
            int i = 1;
            preparedStatement.setLong(i++, id);
            
            /* Execute query. */
            ResultSet resultId = preparedStatement.executeQuery();
            log.debug(queryString);

            EventLogVO vo=null;
            while(resultId.next()){
            	long idNew = resultId.getLong("id");
            	Timestamp fecha = resultId.getTimestamp("fch");
            	char tipo = resultId.getString("tipo").charAt(0);
            	String origen = resultId.getString("origen");
            	String destino = resultId.getString("destino");
            	String texto = resultId.getString("texto");
            	String observaciones = resultId.getString("observaciones");
            	vo= new EventLogVO(idNew,fecha, tipo, origen, destino, texto, observaciones);
            }
            if (vo==null){
                throw new InstanceNotFoundException(id, EventLogVO.class.getName());
            }
            return vo;
    
        } catch (SQLException e) {
            throw new InternalErrorException(e);
        } catch (InstanceNotFoundException e) {
            throw e;
        } finally {
            GeneralOperations.closeStatement(preparedStatement);
        }
	}
	
	public Collection findByType(Connection connection, char type)
		throws InternalErrorException{

		PreparedStatement preparedStatement = null;
	    
        try {
           
            String queryString = "SELECT * FROM logeventos WHERE tipo= ?";
            
            preparedStatement = connection.prepareStatement(queryString);
    
            /* Fill "preparedStatement". */
            int i = 1;
            preparedStatement.setString(i++, ""+type);
    
            /* Execute query. */
            ResultSet resultId = preparedStatement.executeQuery();
            log.debug(queryString);
            
            Collection coll=new ArrayList();
            EventLogVO vo=null;
            while(resultId.next()){
            	long id = resultId.getLong("id");
            	Timestamp fecha = resultId.getTimestamp("fch");
            	char tipo = resultId.getString("tipo").charAt(0);
            	String origen = resultId.getString("origen");
            	String destino = resultId.getString("destino");
            	String texto = resultId.getString("texto");
            	String observaciones = resultId.getString("observaciones");
            	vo= new EventLogVO(id,fecha, tipo, origen, destino, texto, observaciones);
            	
            	coll.add(vo);
            }
            
            return coll;
    
        } catch (SQLException e) {
            throw new InternalErrorException(e);
        } finally {
            GeneralOperations.closeStatement(preparedStatement);
        }
	}
}
